/**
 * Created by xz on 2017/11/20.
 */
console.log('recommendFace');
$('.date-picker').datepicker({autoclose: true}).next().on(ace.click_event, function () {
    $(this).prev().focus();
});
$('#startDate').datepicker('update');
$('#endDate').datepicker('update');

// 保存列数组
var columns = [{
    'field': 'checkStatus',
    'checkbox': true
},
    {
        'field': 'facePictureId',
        'title': 'ID',
        'align': 'center',
        'class': 'hide recommendFaceId'
    },{
        'title': '序号',
        'align': 'center',
        'formatter': function (value, row, index) {
            return index+1;
        }
    },{
        'field': 'facePictureUrl',
        'title': '人脸照',
        'align': 'center',
        'formatter': function (facePictureUrl) {
            return "<image class='showPicture' src='"+facePictureUrl+"' style='width: 30px;'>";
        }
    },
    {
        'field': 'mark',
        'title': '备注',
        'align': 'center'
    },
    {
        'field': 'createDate',
        'title': '添加日期',
        'align': 'center'
    },
    {
        'field': 'display',
        'title': '显示',
        'align': 'center',
        'formatter': function (row) {
            var str = '显示';
            if(!row) {
                str = '隐藏';
            };
            return str;
        }
    },
    {
        'title': '顺序',
        'align': 'center',
        'valign': 'middle',
        'formatter': function (value, row) {
            var html = "<button class='btn btn-sm btn-success glyphicon glyphicon-arrow-up up' data-type='up' style='margin-right: 30px'></button><button class='btn btn-sm btn-success glyphicon glyphicon-arrow-down down' data-type='down' style='margin-right: 30px'></button><button class='btn btn-sm btn-success top'>置顶</button>";
            return html;
        }
    },
    {
        'title': '操作',
        'align': 'center',
        'formatter': function (value, row) {
            var  html = "<button data-newsId='update' class='btn btn-sm btn-success dropNews' style='margin-right: 10px'>编辑新闻</button>";
            return html;
        }
    }];
// 初始化table
var $table =  $("#recommendFace_table").bootstrapTable({
    'url': '/friends/recommandFacePicture/getAllPicturesByPage',
    'queryParams': queryParams,
    'cache': false,
    'toolbar': $('div[data-name="btnCtl"]'),
    // 'toolbarAlign': 'right',
    'striped': true,
    'sidePagination': 'server',
    'pagination': true,
    'sortable': true, //是否启用排序
    'sortOrder': "asc", //排序方式
    'pageSize': globalPageSize,
    'pageList': [],
    'clickToSelect': false,
    'singleSelect': true,
    'maintainSelected': true,
    'smartDisplay': true,
    'ajaxOptions':{
        headers: {"Authorization": sessionStorage.token}
    },
    'responseHandler': function (resb) {
        dataLength = resb.data.total;
        // return resb;
        console.log(resb);
        return {
            'total': resb.data.total,
            'rows': resb.data.content
        }
    },
    'onCheck': function() {
        $("button[data-target='#deleteModal'], button[data-target='#updateModal']").removeAttr("disabled");
    },
    'onUncheck': function() {
        $("button[data-target='#deleteModal'], button[data-target='#updateModal").attr("disabled", 'true');
    },
    // 'onPageChange': function () {
    //     if ($("#recommendFace_table").bootstrapTable('getSelections')[0]) {
    //         $("#recommendFace_table").bootstrapTable('uncheckBy', {
    //             field: 'playCount',
    //             values: [$("#recommendFace_table").bootstrapTable('getSelections')[0].playCount]
    //         });
    //     }
    // },
    'columns': columns
});

//请求服务数据时所传参数
function queryParams(params){
    return {
        type: $('#type_search').val(),
        limit : params.limit, //每一页的数据行数，默认是上面设置的10(pageSize)
        offset : params.offset
    }
};

//切换首页推荐还是相册推荐
$('#type_search').change(function () {
    if($(this).val() === 'newsmaker') {
        columns = [{
            'field': 'checkStatus',
            'checkbox': true
        },
            {
                'field': 'facePictureId',
                'title': 'ID',
                'align': 'center',
                'class': 'hide recommendFaceId'
            },{
                'title': '序号',
                'align': 'center',
                'formatter': function (value, row, index) {
                    return index+1;
                }
            },{
                'field': 'facePictureUrl',
                'title': '人脸照',
                'align': 'center',
                'formatter': function (facePictureUrl) {
                    return "<image class='showPicture' src='"+facePictureUrl+"' style='width: 30px;'>";
                }
            },
            {
                'field': 'mark',
                'title': '备注',
                'align': 'center'
            },
            {
                'field': 'createDate',
                'title': '添加日期',
                'align': 'center'
            },
            {
                'field': 'display',
                'title': '显示',
                'align': 'center',
                'formatter': function (row) {
                    var str = '显示';
                    if(!row) {
                        str = '隐藏';
                    };
                    return str;
                }
            },
            {
                'title': '顺序',
                'align': 'center',
                'valign': 'middle',
                'formatter': function (value, row) {
                    var html = "<button class='btn btn-sm btn-success glyphicon glyphicon-arrow-up up' data-type='up' style='margin-right: 30px'></button><button class='btn btn-sm btn-success glyphicon glyphicon-arrow-down down' data-type='down' style='margin-right: 30px'></button><button class='btn btn-sm btn-success top'>置顶</button>";
                    return html;
                }
            },
            {
                'title': '操作',
                'align': 'center',
                'formatter': function (value, row) {
                    var  html = "<button data-newsId='update' class='btn btn-sm btn-success dropNews' style='margin-right: 10px'>编辑新闻</button>";
                    return html;
                }
            }];
    }else {
        columns = [{
            'field': 'checkStatus',
            'checkbox': true
        },
            {
                'field': 'facePictureId',
                'title': 'ID',
                'align': 'center',
                'class': 'hide recommendFaceId'
            },{
                'title': '序号',
                'align': 'center',
                'formatter': function (value, row, index) {
                    return index+1;
                }
            },{
                'field': 'facePictureUrl',
                'title': '人脸照',
                'align': 'center',
                'formatter': function (facePictureUrl) {
                    return "<image class='showPicture' src='"+facePictureUrl+"' style='width: 30px;'>";
                }
            },
            {
                'field': 'mark',
                'title': '备注',
                'align': 'center'
            },
            {
                'field': 'createDate',
                'title': '添加日期',
                'align': 'center'
            },
            {
                'field': 'display',
                'title': '显示',
                'align': 'center',
                'formatter': function (row) {
                    var str = '显示';
                    if(!row) {
                        str = '隐藏';
                    };
                    return str;
                }
            },
            {
                'title': '顺序',
                'align': 'center',
                'valign': 'middle',
                'formatter': function (value, row) {
                    var html = "<button class='btn btn-sm btn-success glyphicon glyphicon-arrow-up up' data-type='up' style='margin-right: 30px'></button><button class='btn btn-sm btn-success glyphicon glyphicon-arrow-down down' data-type='down' style='margin-right: 30px'></button><button class='btn btn-sm btn-success top'>置顶</button>";
                    return html;
                }
            }];
    }
    $("#recommendFace_table").bootstrapTable('destroy');
    $("#recommendFace_table").bootstrapTable({
        'url': '/friends/recommandFacePicture/getAllPicturesByPage',
        'queryParams': queryParams,
        'cache': false,
        'toolbar': $('div[data-name="btnCtl"]'),
        // 'toolbarAlign': 'right',
        'striped': true,
        'sidePagination': 'server',
        'pagination': true,
        'sortable': true, //是否启用排序
        'sortOrder': "asc", //排序方式
        'pageSize': globalPageSize,
        'pageList': [],
        'clickToSelect': false,
        'singleSelect': true,
        'maintainSelected': true,
        'smartDisplay': true,
        'ajaxOptions':{
            headers: {"Authorization": sessionStorage.token}
        },
        'responseHandler': function (resb) {
            dataLength = resb.data.total;
            // return resb;
            console.log(resb);
            return {
                'total': resb.data.total,
                'rows': resb.data.content
            }
        },
        'onCheck': function() {
            $("button[data-target='#deleteModal'], button[data-target='#updateModal']").removeAttr("disabled");
        },
        'onUncheck': function() {
            $("button[data-target='#deleteModal'], button[data-target='#updateModal").attr("disabled", 'true');
        },
        'columns': columns
    });
});

/**
 * 修改顺序
 */
function changeSort(facePictureId, direction) {
    $.ajaxSetup({cache:false});
    $.ajax({
        type: "POST",
        url: "/friends/recommandFacePicture/changeSort",
        data: {
            'facePictureId': facePictureId,
            'direction': direction
        },
        dataType: 'json',
        beforeSend: function (request) {
            request.setRequestHeader("Authorization", localStorage.token);
        },
        success: function (resb) {
            if(resb.success) {
                // alert('交换成功');
                $("#recommendFace_table").bootstrapTable("refresh");
            }else{
                alert(resb.message);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        }
    });
};

/**
 * 编辑新闻
 */
$('.row').on('click','.dropNews',function () {
    sessionStorage.setItem('facePictureId', $(this).parent().siblings('.recommendFaceId').html());
    $("#main-content").empty();
    loadPage('faceNewsList/faceNewsList.html');
});

/**
 * 音乐操作(新增，更新，删除)
 * @param action [add/update/remove]
 * @param data
 *               [add/update 数据结构 {name: string, description: string, listAuthorityId: array} ]
 *               [delete 数据结构 {adminId: int}]
 * @param async/scync [default async]
 */
function Management(action, data, async) {
    var url = null;
    (async === false) ? async = false : async = true;
    if (action === 'add') {
        url = '/friends/recommandFacePicture/addPicture';
    } else if (action === 'update') {
        url = '/friends/recommandFacePicture/updatePicture';
    } else if(action === 'delete') {
        url = '/friends/recommandFacePicture/deletePicture';
    }

    $.ajaxSetup({cache:false});
    return $.ajax({
        type: "POST",
        url: url,
        data: data,
        dataType: 'json',
        async: async,
        beforeSend: function (request) {
            request.setRequestHeader("Authorization", localStorage.token);
        },
        success: function (resb) {
            // alert(resb.message);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            // console.log(XMLHttpRequest, textStatus, errorThrown);
            if(textStatus=='timeout'){
                ajaxTimeOut.abort(); //取消请求
                alert("请求超时");
            };
            alert(textStatus);
        }
    });
};

/**
 * 条件查询音乐
 */
// $("#dataSearch").click(function () {
//     return musicQuery();
// });

/**
 * 新增模态框显示
 */
$("#addModal").on('show.bs.modal', function () {
    $('#show_image01').attr('src', '');
    $('#add_mark').val('');
});

/**
 * 修改模态框显示
 */
$("#updateModal").on('show.bs.modal', function () {
    var tableData = $("#recommendFace_table").bootstrapTable('getSelections')[0];
    $('#update_id').val(tableData.facePictureId);
    // $('#show_image').src('')
    $('#update_imageUrl').val(tableData.facePictureUrl);
    $('#update_mark').val(tableData.mark);
    $('#update_attribute input:radio[name="updateRadio"]').eq(tableData.display).prop('checked', true);
    $("#updateType").val(tableData.type);
    var input = $('#update_attribute input:radio[name="updateRadio"]');
    input.eq(0).val() === tableData.display+'' ? input.eq(0).prop('checked', true) : input.eq(1).prop('checked', true);
});

//查看图片大图
$('#recommendFace_table').on('click', '.showPicture', function () {
    $('#pictureModal').modal('show');
    $('#pictureModal img').attr('src', $(this).attr('src'));
});

/**
 * 点击修改顺序
 */
$("#recommendFace_table").on('click', '.up, .down', function () {
    var facePictureId,
           direction;
    facePictureId = $(this).parent().siblings('.recommendFaceId').html();
    if($(this).attr('data-type') === 'up') {
        direction = 'up';
    }else {
        direction = 'down';
    };
    changeSort(facePictureId, direction);
});

//跳转到失踪儿童页面
$('#lostChild').click(function () {
    loadPage('lostChild/lostChild.html');
});

//跳转到上报失踪儿童页面
$('#reportLostChild').click(function () {
    loadPage('reportLostChild/reportLostChild.html');
});

//置顶
$("#recommendFace_table").on('click', '.top', function () {
    var facePictureId = $(this).parent().siblings('.recommendFaceId').html();
    $.ajaxSetup({cache:false});
    $.ajax({
        type: "GET",
        url: "/friends/recommandFacePicture/topPicture?facePictureId=" + facePictureId,
        dataType: 'json',
        beforeSend: function (request) {
            request.setRequestHeader("Authorization", sessionStorage.token);
        },
        success: function (resb) {
            if(resb.success) {
                // alert('交换成功');
                $("#recommendFace_table").bootstrapTable("refresh");
            }else{
                alert(resb.message);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        }
    });
});

/**
 * 文件上传
 */
//获取添加文件按钮里面的所有文件并发给后台
$('.addFiles, .updateFiles').on('change',function (e) {
    // var paths = document.getElementById("addFiles").files;
    var paths = this.files;
    console.log(this);
    if(paths.length==0)
    {
        alert("请选择文件");
        return;
    }
    //我们可以预先定义一个FormData对象
    var formData=new FormData();
    // formData.append("file",paths);
    for(var i=0;i<paths.length;i++)
    {
        //将每个文件设置一个string类型的名字，放入到formData中，这里类似于setAttribute("",Object)
        formData.append("file",paths[i]);
    }
    var target = $(this).parents('.form-group').find(':text');
    var img = $(this).parents('.form-group').find('img');
    addFiles(formData, target, img);
    return false;
});

//添加文件的ajax
function addFiles(formData, target, img) {
    return $.ajax({
        url: '/common/uploadFile',
        type: 'POST',
        cache: false,
        data:formData,
        //这个参数是jquery特有的，不进行序列化，因为我们不是json格式的字符串，而是要传文件
        processData: false,
        //注意这里一定要设置contentType:false，不然会默认为传的是字符串，这样文件就传不过去了
        contentType: false,
        success:function(resp){
            // alert("文件上传成功");
            var data = resp.data;
            target.val(data.url);
            if(img) {
                img.attr('src', data.url)
            };
        },
        error:function (err) {

        }
    });
};

/**
 * 新增,更新,删除角色表单提交
 */
$("#addForm, #updateForm, #deleteForm, #addTypeForm").submit(function () {
    var type = $(this).data("type"),
        $modal = $("#" + type + "Modal"),
        tableData = $("#recommendFace_table").bootstrapTable('getSelections')[0],
        $that = $(this);

    // 模式选择,设置不同的data和url
    if (type === 'delete') {
        data = {
            'facePictureId': tableData.facePictureId
        };
    } else if (type === 'add') {
        var obj = jQuery("#addForm").validationEngine('validate', {
            promptPosition: "centerRight",
            autoPositionUpdate: true,
            validationEventTrigger:'blur',
            binded:true,
            showOneMessage:true
        });
        if (!obj) {
            return false;
        }
        data = {
            'pictureUrl': $('#add_imageUrl').val(),
            'mark': $('#add_mark').val(),
            'type': $('#addType').val(),
            'display': $('#add_attribute input:radio[name="addRadio"]:checked').val()
        };
    } else if (type === 'update') {
        data = {
            'facePictureId': $('#update_id').val(),
            'pictureUrl': $('#update_imageUrl').val(),
            'mark': $('#update_mark').val(),
            'type': $('#updateType').val(),
            'display': $('#update_attribute input:radio[name="updateRadio"]:checked').val()
        };
    }

    // $('#addModal').modal('hide');
    // $('#updateModal').modal('hide');
    // $('#deleteModal').modal('hide');
    $modal.modal('hide');
    // 完成ajax后刷新表格数据
    Management(type, data).done(function () {
        $("#recommendFace_table").bootstrapTable("refresh");
        $("button[data-target='#updateModal'], button[data-target='#deleteModal']").attr("disabled", 'true');
        $that.parents('.modal-content').find('form')[0].reset();
    });

    // 阻止表格冒泡事件
    return false;
});
